import {
  _postOrg,
  _postJobs,
  _postLabels
} from '../../service/api/common'
import {
  _getOrgByType,
  _getListChildrenByCode,
  _getOrganizationAndChildrenByType,
  _postOrgAdd,
  _update,
  _getOrganizationByCode,
  _deleteOrg,
  _updateStatus,
  _postPageNextLevelChildrenByCode,
  _getOrgUserList,
  _postChangeRef,
  _getDataUserList,
  _postChangePrincipal,
  _getAllOrgList,
  _getPriSelect
} from '../../service/api/organization'
import eventBus from '../../service/eventBus.js'
const types = {
  SET_INIT: 'SET_INIT',
  SET_DEPARTMENT_MODAL: 'SET_DEPARTMENT_MODAL',
  SET_STRUCTURE_ROOT: 'SET_STRUCTURE_ROOT',
  SET_STRUCTURE: 'SET_STRUCTURE',
  SET_LABELS: 'SET_LABELS',
  SET_JOBS: 'SET_JOBS',
  SET_BASE_INFO: 'SET_BASE_INFO',
  SET_ORGANIZATION: 'SET_ORGANIZATION',
  SET_TABLE_DATA: 'SET_TABLE_DATA',
  SET_ORG_SELECTED: 'SET_ORG_SELECTED',
  SET_TABLE_PARAMS: 'SET_TABLE_PARAMS',
  SET_PAGINATION: 'SET_PAGINATION',
  SET_STRUCTURE_ROOT_TREE: 'SET_STRUCTURE_ROOT_TREE',
  SET_STRUCTURE_MAP: 'SET_STRUCTURE_MAP',
  SET_LOADING: 'SET_LOADING',
  SET_CURRENT_TREE: 'SET_CURRENT_TREE'
}

const defaultParams = {
  id: '',
  page: 1,
  size: 10,
}

const state = {
  departmentModal: {
    show: false,
    obj: null
  },
  loading: {
    tableLoading: false,
    treeLoading: false
  },
  orgSelected: '',
  structureOption: [],
  structureTree: [],
  structureRootTree: [],
  labels: [],
  jobs: [],
  baseInfo: {},
  organization: [],
  tableData: [],
  tableParams: {
    ...defaultParams
  },
  pagination: null,
  structureTreeMap: {},
  currentTreeData: {}
}

const mutations = {
  // eslint-disable-next-line no-unused-vars
  [types.SET_CURRENT_TREE](state, data = {}) {
    state.currentTreeData = data
  },
  [types.SET_INIT](state, all) {
    if (all) {
      state = Object.assign(state, {
        departmentModal: {
          show: false,
          obj: null
        },
        orgSelected: '',
        structureOption: [],
        structureTree: [],
        structureRootTree: [],
        labels: [],
        jobs: [],
        baseInfo: {},
        organization: [],
        tableData: [],
        tableParams: {
          ...defaultParams
        },
        pagination: null,
        structureTreeMap: {}
      })
    } else {
      state = Object.assign(state, {
        departmentModal: {
          show: false,
          obj: null
        },
        structureOption: [],
        structureTree: [],
        structureRootTree: [],
        baseInfo: {},
        tableData: [],
        tableParams: {
          ...defaultParams
        },
        pagination: null,
        structureTreeMap: {}
      })
    }

  },
  [types.SET_DEPARTMENT_MODAL](state, obj) {
    state.departmentModal = obj
  },
  [types.SET_ORG_SELECTED](state, string) {
    state.orgSelected = string
  },
  [types.SET_STRUCTURE_ROOT](state, arr) {
    state.structureTree = arr
  },
  [types.SET_STRUCTURE](state, arr) {
    state.structureOption = arr
  },
  [types.SET_LABELS](state, arr) {
    state.labels = arr
  },
  [types.SET_JOBS](state, arr) {
    state.jobs = arr
  },
  [types.SET_BASE_INFO](state, obj) {
    state.baseInfo = obj
  },
  [types.SET_ORGANIZATION](state, arr) {
    state.organization = arr
  },
  [types.SET_TABLE_DATA](state, arr) {
    state.tableData = arr
  },
  [types.SET_TABLE_PARAMS](state, obj) {
    state.tableParams = obj
  },
  [types.SET_PAGINATION](state, obj) {
    state.pagination = obj
  },
  [types.SET_STRUCTURE_ROOT_TREE](state, arr) {
    state.structureRootTree = arr
  },
  [types.SET_STRUCTURE_MAP](state, obj) {
    state.structureTreeMap = {
      ...obj
    }
  },
  [types.SET_LOADING](state, obj) {
    state.loading = {
      ...obj
    }
  },

}

const actions = {
  
  async fetchPriSelect({
    dispatch,
    state
  }, params) {
    const res = await _getPriSelect(params);
    return res && res.status ? res : null
  },
  async fetchAllOrgOptions({
    dispatch,
    state
  }, params) {
    const res = await _getAllOrgList(params);
    return res && res.status ? res : null
  },
  async fetchPutChangePrincipal({
    dispatch,
    state
  }, params) {
    const res = await _postChangePrincipal(params);
    return res && res.status ? res : null
  },
  async fetchDataUserList({
    dispatch,
    state
  }, params) {
    const res = await _getDataUserList(params);
    return res && res.status ? res : null
  },
  async fetchChangeRef({
    dispatch,
    state
  }, params) {
    const res = await _postChangeRef(params);
    return res && res.status ? res : null
  },
  async fetchOrgUserList({
    dispatch,
    state
  }, params) {
    const res = await _getOrgUserList(params);
    return res && res.status ? res : null
  },
  async createDepartment({
    dispatch,
    state
  }) {
    await dispatch('fetchStrucureTree', {})
    dispatch('setDepartmentModalShow', {
      show: true,
      obj: null,
      currentTreeData: state.currentTreeData
    })
  },
  async editDepartment({
    dispatch,
    state
  }, obj) {
    await dispatch('fetchStrucureTree', obj)
    dispatch('setDepartmentModalShow', {
      show: true,
      obj
    })
  },
  closeModal({
    dispatch
  }) {
    dispatch('setDepartmentModalShow', {
      show: false,
      obj: null
    })
  },
  setDepartmentModalShow({
    commit
  }, obj) {
    commit(types.SET_DEPARTMENT_MODAL, obj)
  },
  async setOrgSelected({
    dispatch,
    commit
  }, val) {
    commit(types.SET_ORG_SELECTED, val)
    commit(types.SET_LOADING, {
      treeLoading: true
    })
    await dispatch('initState')
    // await dispatch('fetchStrucureTree', val)
    await dispatch('fetchStructureRoot', val)
  },
  // eslint-disable-next-line no-unused-vars
  async fetchStructureRoot({
    commit
  }, value) { // 获取左侧侧组织树
    // commit(types.SET_LOADING, {treeLoading:true})
    // let res = await _getOrgByType(value)
    commit(types.SET_LOADING, {
      treeLoading: true,
      tableLoading:true,
    })
    let res = await _getOrganizationAndChildrenByType()
    commit(types.SET_LOADING, {
      treeLoading: false
    })
    if (res && res.status && res.data) {
      console.log(res.data)
      // let data = [{
      //   code: res.data.code,
      //   name: res.data.name,
      //   status: res.data.status,
      //   childrenList: res.data.childrenList
      // }]
      commit(types.SET_STRUCTURE_ROOT_TREE, res.data)
      return res.data
    } else {
      commit(types.SET_STRUCTURE_ROOT_TREE, [])
      return []
    }
  },
  // eslint-disable-next-line no-unused-vars
  async fetchStructureLeaf({
    commit
  }, obj) {
    let res = await _getListChildrenByCode({
      code: obj.code
    })
    if (res && res.status) {
      let data = res.data.map(item => ({
        code: item.code,
        name: item.name,
        status: item.status,
        childrenList: []
      }))
      return data
      //  commit(types.SET_STRUCTURE_ROOT, data)
    }
    return []
  },
  async fetchStrucureTree({
    commit
  }, obj={}) { //获取新增部门下拉列表
    let res = await _getOrganizationAndChildrenByType()
    if (res && res.status && res.data) {
      let data = res.data
      console.log(data)
      let noData = {
        code: '-1',
        name: '无',
        status: '',
        childrenList: null
      }
        let code = obj.code
        if(code) {
          let childrenListDisable = (arr) => {
            arr.forEach((item) => {
              item.disabled = true
              if(item.childrenList && item.childrenList.length) {
                childrenListDisable(arr.childrenList)
              }
            })
            
          }
          let findSelf = (arr,code) => {
            arr.forEach((item) => {
              if(item.code == code) {
                item.disabled = true
                if(item.childrenList && item.childrenList.length) {
                  childrenListDisable(item.childrenList)
                }
              }else {
                console.log(item.childrenList)
                if(item.childrenList && item.childrenList.length) {
                  findSelf(item.childrenList,code)
                }
              }
            })
            
          }
          findSelf(data,code)
        }
        
      commit(types.SET_STRUCTURE, [noData, ...data])
    } else {
      commit(types.SET_STRUCTURE, [])
    }
  },
  async fetchLabels({
    commit
  }) {
    let res = await _postLabels()
    if (res && res.status) {
      let data = res.data.map(item => ({
        value: JSON.stringify({
          code: item.code,
          name: item.name,
          id: item.id
        }),
        status: item.status,
        label: item.name,
        id: item.id
      }))
      commit(types.SET_LABELS, data)
    }
  },
  async fetchJobs({
    commit
  }) {
    let res = await _postJobs()
    if (res && res.status) {
      let data = res.data.map(item => ({
        value: JSON.stringify({
          code: item.code,
          name: item.name,
          id: item.id
        }),
        status: item.status,
        label: item.name,
        id: item.id
      }))
      commit(types.SET_JOBS, data)
    }

  },
  async fetchBaseInfo({
    commit
  }, code) {
    // eslint-disable-next-line no-console
    let res = await _getOrganizationByCode(code)
    if (res && res.status) {
      commit(types.SET_BASE_INFO, res.data)
    }
  },
  async fetchTableData({
    commit,
    dispatch,
    state
  }, params) {
    commit(types.SET_LOADING, {
      tableLoading: true
    })
    let res = await _postPageNextLevelChildrenByCode(params)
    commit(types.SET_LOADING, {
      tableLoading: false
    })
    if (res && res.status) {
      let data = res.data.list || []
      // if (data.length === 0 && res.data.total) {
      //   dispatch('fetchTableData', {
      //     ...state.tableParams,
      //     page: res.data.lastPage
      //   })
      //   return
      // }
      commit(types.SET_TABLE_DATA, data)
      commit(types.SET_TABLE_PARAMS, {
        ...params,
        page: res.data.pageNum,
      })
      commit(types.SET_PAGINATION, {
        page: res.data.pageNum,
        size: params.size,
        total: res.data.total
      })
    }
  },
  async fetchOrganizationInfo({
    dispatch,
    commit
  }, code) { // 获取组织列表
    // await dispatch('fetchBaseInfo', code)
    commit(types.SET_LOADING, {
      tableLoading: true
    })
    await dispatch('fetchTableData', {
      ...defaultParams,
      id: code
    })
    commit(types.SET_LOADING, {
      tableLoading: false
    })
  },
  async fetchOrganization({
    dispatch,
    commit
  }) {
    let res = await _postOrg()
    if (res && res.status) {
      let data = res.data.map(item => ({
        value: item.dictValue,
        label: item.dictValue
      }))
      commit(types.SET_ORGANIZATION, data)
      if (data.length) {
        await dispatch('setOrgSelected', data[0].value)
      }

    }
  },
  async updateDepart({
    dispatch,
    state
  }, params) {
    let res = await _update(params)
    if (res && res.status) {
      dispatch('fetchTableData', state.tableParams)
      // let data = await dispatch('fetchStructureLeaf', {
      //   code: params.parentCode
      // })
      // eventBus.$emit('updateNode', data)
    }
    return res
  },
  // eslint-disable-next-line no-unused-vars
  async submitDepart({
    dispatch,
    commit,
    state
  }, form) {
    let res = await _postOrgAdd(form)
    if (res && res.status) {
      if(state.structureRootTree.length == 0) {
        await dispatch('fetchStructureRoot')
        eventBus.$emit('updateNode', {isAddFirst:true,code:form.code})
        return res
      }
      await dispatch('fetchStructureRoot')
      eventBus.$emit('updateNode', {isAdd:true,code:form.code})
    }
    return res
  },
  async deleteOrg({
    dispatch,
    state
  }, params) {
    let res = await _deleteOrg(params.id)
    if (res && res.status) {
      console.log(state.tableParams,state.pagination)
      if(params.id == state.tableParams.id) {
        await dispatch('fetchStructureRoot')
        eventBus.$emit('updateNode', {isDelSelf:true})
        return true
      }else {
        //删除的不是自己而且数据大于一条，刷新树和表格，设置树选中节点
        if(state.pagination.total>1){
          // dispatch('fetchTableData', state.tableParams)
          let data = await dispatch('fetchStructureRoot')
          eventBus.$emit('updateNode', {isDelOtherOrg:true})
          return true
        }
        dispatch('fetchTableData', state.tableParams)
        let data = await dispatch('fetchStructureRoot')
        eventBus.$emit('updateNode', data)
        return true

      }
    }
    return false
  },
  async updateStatus({
    dispatch,
    state
  }, obj) {
    let res = await _updateStatus(obj.id, obj.status)
    if (res && res.status) {
      dispatch('fetchTableData', state.tableParams)
      return true
    }
    return false
  },
  async setStructureMap({
    commit
  }, obj) {
    commit(types.SET_STRUCTURE_MAP, obj)
  },
  initState({
    commit
  }, all = false) {
    commit(types.SET_INIT, all)
  }
}

const getters = {
  departmentModal: state => state.departmentModal,
  structureOption: state => state.structureOption,
  structureTree: state => state.structureTree,
  labels: state => state.labels,
  jobs: state => state.jobs,
  baseInfo: state => state.baseInfo,
  organization: state => state.organization,
  tableData: state => state.tableData,
  orgSelected: state => state.orgSelected,
  tableParams: state => state.tableParams,
  pagination: state => state.pagination,
  structureRootTree: state => state.structureRootTree,
  structureMap: state => state.structureMap,
  loading: state => state.loading,
  currentTreeData: state => state.currentTreeData
}


export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}